<template>
  <a-input-search
      v-model:value="searchText"
      placeholder="input search text"
      enter-button="Search"
      size="large"
      @search="onSearch"
  />
  <Divider/>
  <a-tabs v-model:activeKey="activeKey" @change="OnTabChange">
    <a-tab-pane key="post" tab="文章">
      <Article :post-list="postList"/>
    </a-tab-pane>
    <a-tab-pane key="user" tab="用户表" force-render>
      <User :user-list="userList"/>
    </a-tab-pane>
    <a-tab-pane key="picture" tab="图片">
      <Picture :picture-list="pictureList"/>
    </a-tab-pane>
  </a-tabs>
</template>

<script setup lang="ts">

import {ref, watchEffect} from "vue";
import Article from "@/components/Article.vue";
import User from "@/components/User.vue";
import Picture from "@/components/Picture.vue";
import Divider from "@/components/Divider.vue";
import {useRouter,useRoute} from "vue-router";
import myAxios from "@/plugins/myAxios";
import {message} from "ant-design-vue";
const router = useRouter();
const route = useRoute();
const activeKey = route.params.category;
const searchText = ref(route.query.text || "");
const searchParams = ref({
  text:'',
  type:activeKey
})

const postList = ref([]);
const userList = ref([]);
const pictureList = ref([]);

/**
 * 加载聚合全部数据
 * @param params
 */
const loadAllData =(params:any)=>{
  const query = {
    ...params,
    searchText:params.text,
  }

  myAxios.post("/search/list/page/vo",query)
      .then((res:any) =>{
        postList.value = res.postList;
        userList.value = res.userList;
        pictureList.value = res.pictureList;
      });
}


/**
 * 根据type加载单类数据
 * @param params
 */
const loadData =(params:any)=>{
  const { type } = params;
  if(!type)
  {
    message.error("类别为空");
    return
  }
  const query = {
    ...params,
    searchText:params.text,
  }

  myAxios.post("/search/list/page/vo",query)
      .then((res:any) =>{
        if (type === "post"){
          postList.value = res.list;
        }else if(type ==="user") {
          userList.value = res.list;
        }else if(type === "picture"){
          pictureList.value = res.list;
        }});
}

//首次请求
loadAllData(searchParams);

watchEffect(()=>{
  searchParams.value = {
    text: route.query.text,
    type: route.params.category,
  }as any;
  loadData(searchParams.value);
})

const onSearch = (value:string ) => {
  console.log(value);
  router.push({
    query:{
      ...searchParams.value,
      text: value,
    }
  });
};

const OnTabChange = (key:string) =>{
  router.push({
    path:`/${key}`,
    query:{
      ...searchParams.value,
      type:key
    }

  })
}

</script>
